//#!/usr/bin/env node

var http = require('http'),
    querystring =require('querystring'),
    url = require('url'),
    serIp = "192.168.4.107";//"192.168.5.119",
    fs = require('fs'),
    dateFormat = require('./Date+Addition').format;;

var keyFuncs = {};
if(process.argv[2]){
    console.log(process.argv[2])
    serIp = process.argv[2]
}

String.prototype.trim=function() {
    
    return this.replace(/(^\s*)|(\s*$)/g,'');
}

function addRout(key,func){
    keyFuncs[key] = func;
}
addRout("/web",function (data){
        console.log("web "+JSON.stringify(data));
        });

function getClientIp(req) {
    return req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
};
http.createServer(function (req, res) {
                  var filePath = url.parse(req.url).hostname;
                  var pathname = url.parse(req.url).pathname;
                  filePath = filePath.replace(/\./g,"_");
                  var filename = fileNameFromUrl(req.url);
                  var func = keyFuncs[pathname];
                  var ip = getClientIp(req);
                  console.log("\n"+req.url);
                  console.log(ip);
                  console.log("method:"+req.method);
                  if(typeof func === "function"){
                    //方法一arg => aa=001&bb=002
                    //var arg = url.parse(req.url).query;
                    //方法二arg => { aa: '001', bb: '002' }
                    var arg = url.parse(req.url, true).query;
                    func(arg);
                  }
                  var post = '';
                  req.on('data',function(chunk){
                         post+=chunk;
                         });
                  req.on('end',function(){
                         //拼成get的url
                         var postUrl = req.url;
                         if(postUrl.indexOf("?") == -1){
                            postUrl = req.url+"?"+post;
                         }else{
                            postUrl = req.url+post;
                         }
                         console.log("post:"+postUrl);
                         //console.log(querystring.parse(post));
                         if(req.method == "get"){
                         return;
                         }
                         http.get(postUrl, function(res1,by) {
                                  var jsonStr = null;
                                  res1.on('data', function(chunk){
                                          jsonStr += chunk
                                          });
                                  res1.on('end', function(){
                                          var fileStr = null;
                                          var contentType = res1.headers["content-type"];
                                          console.log("content-type:"+contentType);
                                          if(typeof(contentType) == "undefined"){
                                            contentType = "text/html; charset=utf-8";
                                          }else{
                                            if(contentType.indexOf("image") == -1){
                                                jsonStr = (jsonStr +"").slice(4);
                                                fileStr = jsonStr;
                                                console.log("返回数据：\n"+jsonStr);
                                            }else{
                                                fileStr = '{"data":"图片文件流"}'
                                                console.log("返回图片数据\n");
                                            }
                                          }
                                          
                                          res.setHeader('Content-Type',contentType);
                                          if(contentType.indexOf("image") == -1){
                                            res.write(new Buffer(0)+jsonStr);
                                          }else{
                                            res.write(jsonStr);
                                          }
                                          res.end();
                                          saveMsg(fileStr,filePath,filename,postUrl);
                                          });
                                  res1.on('error', function(e){
                                          console.log("发生异常：\n" + e.message);
                                          res.end();
                                          });
                                  }).on('error', function(e) {
                                        console.log("发生异常：\n"+e);
                                        res.end();
                                        });
                         });
                  if(req.method == "get"){
                  http.get(req.url, function(res1) {
                           var jsonStr = null;
                           res1.on('data', function(chunk){
                                   jsonStr += chunk
                                   });
                           res1.on('end', function(){
                                   console.log("请求url：\n" + req.url);
                                   var fileStr = null;
                                   var contentType = res1.headers["content-type"];
                                   console.log("content-type:"+contentType);
                                   if(typeof(contentType) == "undefined"){
                                        contentType = "text/html; charset=utf-8";
                                   }else{
                                          
                                            if(contentType.indexOf("image") == -1){
                                                jsonStr = (jsonStr +"").slice(4);
                                                fileStr = jsonStr;
                                                console.log("返回数据：\n"+jsonStr);
                                            }else{
                                                fileStr = '{"data":"图片文件流"}'
                                                console.log("返回图片数据\n");
                                            }
                                          }
                                   
                                   res.setHeader('Content-Type',contentType);
                                   if(contentType.indexOf("image") == -1){
                                    res.write(new Buffer(0)+jsonStr);
                                   }else{
                                    res.write(jsonStr);
                                   }
                                   res.end();
                                   saveMsg(fileStr,filePath,filename,postUrl);
                                   });
                           res1.on('error', function(e){
                                   //console.log("请求url：\n" + url);
                                   console.log("发生异常：\n" + e.message);
                                   res.end();
                                   });
                           }).on('error', function(e) {
                                 console.log("发生异常：\n"+e);
                                 res.end();
                                 });
                  }
                  }).listen(3000, serIp);
console.log('Server running at http://'+serIp+':3000/');


function fileNameFromUrl(requrl){
    var pathname = url.parse(requrl).pathname;
    var filename = pathname.split("/").pop();
    var arr = filename.split(".");
    if(arr[0].length>0){
        filename = arr[0];
    }else{
        filename = fileNameFromTimeNow();
    }
    return filename;
}

function fileNameFromTimeNow(){
    var date = new Date();
    filename = date.format("yyyy_MM_dd");
    console.log("filenameTime:"+filename);
    return filename;
}

function mkdirSyncIfNeed(path){
    var arr = path.split("/");
    var checkPath = arr[0]+"/";
    try{
        for (var i = 0; i < arr.length; i++) {
            if (!fs.existsSync(checkPath)) {
                fs.mkdirSync(checkPath);
                //console.log("mkdirSync:"+checkPath+" "+i);
                for(var j = i+1; j < arr.length; j++){
                    checkPath += arr[j]+"/";
                    fs.mkdirSync(checkPath);
                    //console.log("mkdirSync:"+checkPath+" "+j);
                }
                return;
            }
            checkPath += arr[i+1]+"/";
        }
    }catch(e){
        console.log(e);
    }
}

function saveMsg(str,path,fileName,requrl){
    var fileExt = ".json"
    var fileStr = str;
    if(fileName.length>15){
        fileName = fileName.substring(0,15);
    }
    path = "../log/"+fileNameFromTimeNow()+"/" + path;
    try{
        var jsObj = null;
        var date = new Date();
        var dateStr = date.format("yyyy-MM-dd hh:mm:ss");
        jsObj = JSON.parse(str);
        fileStr = JSON.stringify({"serviceData":jsObj,"saveTime":dateStr,"url":requrl}, null, 2)+"\r\n\r\n";
    }catch(e){
        fileExt = ".txt"
    }
    mkdirSyncIfNeed(path);
    if (!fs.existsSync(path)) {
        console.log("no filepathname:"+path);
        return;
    }
    var filePathName = path+"/"+fileName+fileExt;
    console.log("filepathname:"+filePathName);
    if (!fs.existsSync(filePathName)) {
        fs.writeFile(filePathName,"\nurl:"+requrl+"\n"+fileStr);
    }else{
        fs.appendFile(filePathName,","+fileStr, function (err) {
                      if (!err) {
                      //console.log('Wrote data to file.txt');
                      } else {
                      //throw err;
                      console.log(err);
                      }
                      });
    }
}
